package com.itheima.reflect;
import org.junit.jupiter.api.Test;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class testReflect {
    @Test
    public void testGetClassObject() throws Exception {
        // 获取 Class 对象三种方式
        Class<Student> c1 = Student.class;
        System.out.println(c1.getName());
        System.out.println(c1.getSimpleName());

        Class c2 = Class.forName("com.itheima.reflect.Student");

        Student s = new Student();
        Class c3 = s.getClass();
    }

    @Test
    public void testGetConstructor() throws Exception {
        Class<Student> c1 = Student.class;
//        Constructor[] constructors = c1.getConstructors();
        Constructor[] constructors = c1.getDeclaredConstructors();
        for (Constructor c : constructors) {
            System.out.println(c.getName()+"---"+c.getParameterCount());
        }

        Constructor c2 = c1.getDeclaredConstructor(String.class, int.class);
        System.out.println(c2.getName()+"---"+c2.getParameterCount());

        Student tao = (Student) c2.newInstance("tao", 100);
    }

    @Test
    public void testGetField() throws Exception {
        Class<Student> c1 = Student.class;
        Field[] fields = c1.getDeclaredFields();
        for (Field f : fields) {
            System.out.println(f.getName()+"---"+f.getType());
        }
    }

    @Test
    public void testGetMethod() throws Exception {
        Class<Student> c1 = Student.class;
        Method[] methods = c1.getDeclaredMethods();
        for (Method m : methods) {
            System.out.println(m.getName()+"---"+m.getParameterCount());
        }

        Method say = c1.getDeclaredMethod("say");
        say.setAccessible(true); // 获取私有方法的权限
        Student s = new Student();
        Object rs =say.invoke(s);
    }
}
